package com.mymoney.resources;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.mymoney.beans.DeviceBean;
import com.mymoney.exceptions.MyMoneyException;
import com.mymoney.persistence.PersistenceContext;
import com.mymoney.persistence.TransactionalAction;
import com.mymoney.persistence.managers.DeviceManager;
import com.mymoney.utils.ServiceUtils;

@Path("/devices")
public class DeviceResource extends AbstractWebResource{

	@POST
	@Path("/device")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response add(final DeviceBean deviceBean) {

		final PersistenceContext persistenceContext = PersistenceContext.getPersistenceContext();
		try {

			TransactionalAction action = new TransactionalAction() {

				public void run() throws MyMoneyException {
					DeviceManager deviceManager = persistenceContext.getDeviceManager();
					deviceManager.add(deviceBean);
				};

			};
			persistenceContext.run(action);
			return Response.ok("EVALA").build();
		} catch (Exception e) {
			Response response = ServiceUtils.getErrorResponse(111, e);
			return response;
		}
	}

	@GET
	@Path("/device/{deviceUid}")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getByUid(final @PathParam("deviceUid") String deviceUid) {

		PersistenceContext persistenceContext = PersistenceContext.getPersistenceContext();
		try {
			DeviceManager deviceManager = persistenceContext.getDeviceManager();
			DeviceBean deviceBean = deviceManager.getByName(deviceUid);

			return Response.ok(deviceBean).type(MediaType.APPLICATION_JSON).build();
		} catch (Exception e) {
			Response response = ServiceUtils.getErrorResponse(111, e);
			return response;
		}
	}

	@PUT
	@Path("/device/{deviceUid}")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response update(final @PathParam("deviceUid") String deviceUid,
			final DeviceBean deviceBean) {

		final PersistenceContext persistenceContext = PersistenceContext.getPersistenceContext();
		try {

			TransactionalAction action = new TransactionalAction() {

				public void run() throws MyMoneyException {
					DeviceManager deviceManager = persistenceContext.getDeviceManager();
					deviceManager.update(deviceBean, deviceUid);
				};

			};
			persistenceContext.run(action);

			return Response.ok("EVALA").build();
		} catch (Exception e) {
			Response response = ServiceUtils.getErrorResponse(111, e);
			return response;
		}
	}

}
